package com.example.blog.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.module.entity.Message;
import com.example.blog.module.entity.VO.Conversation;
import com.example.blog.module.mapper.MessageMapper;
import com.example.blog.module.service.MessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.module.service.SysUserService;
import com.example.blog.module.utils.BaseContent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zjx
 * @since 2023-04-10
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private final MessageMapper messageMapper;

    private final SysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Conversation> findConversations(Integer page, Integer pageSize) {
        Long userId = BaseContent.get().getId();
        List<Conversation> conversations = new ArrayList<>();
        List<String> conversationIds = messageMapper.findConversations(userId,page,pageSize);
        for (String conversationId: conversationIds
             ) {

            //寻找最晚的 消息
            LambdaQueryWrapper<Message> wrapper =new LambdaQueryWrapper<>();
            wrapper.eq(Message::getConversationId,conversationId);
            wrapper.orderByDesc(Message::getCreateTime);
            wrapper.last("limit 1");
            Message temp = messageMapper.selectOne(wrapper);

            //未读数 必须是 对方发送的 己方接收的 且未读
            LambdaQueryWrapper<Message> wrapper1 =new LambdaQueryWrapper<>();
            wrapper.eq(Message::getConversationId,conversationId);
            wrapper.eq(Message::getToId,userId);
            wrapper.eq(Message::getStatus,0);
            Integer unReadCount = Math.toIntExact(messageMapper.selectCount(wrapper1));

            Conversation conversation = new Conversation();
            conversation.setConversationId(conversationId);
            conversation.setLastMessage(temp.getContent());
            conversation.setLastTime(temp.getCreateTime());
            conversation.setUnReadCount(unReadCount);
            conversation.setAuthor(sysUserService.findUserVoById(temp.getFromId().equals(userId) ? temp.getToId() : temp.getFromId()));
            conversations.add(conversation);
        }
        return conversations;
    }

    @Override
    public int delConversation(String conversationId) {
        LambdaQueryWrapper<Message> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId,conversationId);
        return messageMapper.delete(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Message> conversationDetail(String conversation, Integer pageNum, Integer pageSize) {
        Long userId = BaseContent.get().getId();

        //查询返回
        Page<Message> page =new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getConversationId,conversation);
        wrapper.orderByDesc(Message::getCreateTime);

        //设置已读
        UpdateWrapper<Message> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("conversation_id",conversation);
        wrapper1.eq("to_id",userId);
        wrapper1.eq("status",0);
        wrapper1.set("status",1);
        messageMapper.update(null,wrapper1);

        return messageMapper.selectPage(page,wrapper).getRecords();
    }

    @Override
    public int sendMessage(Long toId,String content) {
        Long userId = BaseContent.get().getId();
        String conversation = toId<userId ? toId+"_"+userId : userId+"_"+toId;

        Message message = new Message();
        message.setContent(content);
        message.setConversationId(conversation);
        message.setCreateTime(new Date());
        message.setFromId(userId);
        message.setId(toId);
        message.setStatus(0L);

        return messageMapper.updateById(message);
    }
}
